<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>通过审批后继续编辑借货订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        var loanId = new Ext.form.Hidden({
          name: 'id'
        });

        var version = new Ext.form.Hidden({
          name: 'lock_version'
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '100%'
        });
        //所有客户
        var customerTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:70px">{number}</div><div style="float:left;width:230px">|{name}</div>| {phone}', '</div></tpl>');
        var customerStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/customer/getAllCustomers?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number',
              convert:function(value,record){
                if (value === ""){
                  return "未设置编号"
                }else{
                  return value;
                }
              }
            }, {
              name: 'name'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'address'
            }])
        });

        var toCustomer = new Ext.form.ComboBox({
          store: customerStore,
          fieldLabel: '到客户',
          allowBlank: false,
          blankText: "客户必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'customer_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: customerTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:"all",
          selectOnFocus:true
        });

        toCustomer.on('select', function(combo, record, index) {
          linkman.setValue(record.get('linkman'));
          phone.setValue(record.get('phone'));
          deliveryAddress.setValue(record.get('address'));
        });

        var addCustomerButton = new Ext.Button({
          text: '添加客户',
          iconCls: 'addItem',
          scale: 'small',
          handler: onAddCustomerButtonClick
        });

        function onAddCustomerButtonClick(){
          newCustomerWin = new Ext.Window({
            layout: 'fit',
            width:618,
            height:300,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            //modal: true,
            title: '添加客户',
            autoLoad: {
              url: "/customer/newCustomer",
              scripts: true
            }
          });
          newCustomerWin.resizable = false;
          newCustomerWin.show();
        }

        //要求发货时间
        var actionDate = new Ext.form.DateField({
          fieldLabel: '发货日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "发货日期必须选择",
          emptyText: '发货日期...',
          anchor: '95%'
        });
        //合同号
        var contractNumber = new Ext.form.TextField({
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = new Ext.form.TextField({
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false,
          anchor: '95%'
        });
        
        //联系电话
        var phone = new Ext.form.TextField({
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false,
          anchor: '95%'
        });

        var deliveryAddress = new Ext.form.TextField({
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '100%'
        });

        //借货员
        var salesTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<div style="float:left; width:35px">{number}</div><div style="float:left;width:55px">|{name}</div>', '</div></tpl>');
        var salesStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/employee/getAllEmployees?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });

        var sales = new Ext.form.ComboBox({
          store: salesStore,
          fieldLabel: '借货员',
          allowBlank: false,
          blankText: "借货员必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'sales_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: salesTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          anchor: '95%',
          selectOnFocus:true
        });
        //--------------------------------------------------------------------------

        var productTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item"><div style="float:left; width:230px">{name}</div><div>', '{is_suit}', '</div></div></tpl>');
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product/getAllProducts?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });

        //供应商产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '供应商产品',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          displayField: 'name',
          anchor: '90%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var loanItemRecord = loanDetailSM.getSelected();
          if (!loanItemRecord) {
            return false;
          }
          if (isDuplicateByProduct(loanDetailDS,record.get('id'),loanItemRecord.id)){
            //删除当前记录
            if (loanItemRecord.get('product_id') != record.get('id')){
              loanDetailDS.remove(loanItemRecord);
            } 
          }else{
            if (loanItemRecord.get('product_id') != record.get('id')){
              loanItemRecord.set('number',record.get('number'));
              loanItemRecord.set('spec',record.get('spec'));
              loanItemRecord.set('unit',record.get('unit'));
              loanItemRecord.set('quantity',1);
              loanItemRecord.set('product_id',record.get('id'));
              //判断套装
              loanItemRecord.set('is_suit',record.get('is_suit'));
            }
          }
        });

        //借货订单列表Grid Store
        var loanDetailDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/loan/getLoanDetailsById'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number',
              mapping: 'product.number'
            }, {
              name: 'product_name',
              mapping:'product.name'
            }, {
              name: 'spec',
              mapping:'product.spec'
            }, {
              name: 'unit',
              mapping:'product.unit'
            }, {
              name: 'description'
            }, {
              name: 'quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'is_suit',
              mapping: 'product.is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }, {
              name: 'description'
            }])
        });
        loanDetailDS.baseParams.loan_id = <%=params[:id]%>;
        loanDetailDS.load();
        
        //生成产品Grid的CM
        var loanDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        //var loanDetailSM = new Ext.grid.RowSelectionModel({singleSelect:true});
        var loanDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),loanDetailSM,{
              header: '产品名称',
              dataIndex: 'product_name',
              editor: productCBB,
              width: 290
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 95
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 40
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              width: 50
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 240,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '90%'
              })
            }
          ]});

        //生成要订单的产品的Grid
        var loanDetailGrid = new Ext.grid.EditorGridPanel({
          store: loanDetailDS,
          cm: loanDetailCM,
          sm: loanDetailSM,
          width: 950,
          height: 290,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = loanDetailGrid.getStore().recordType;
                var record = new Product({
                  product_name: '请选择产品'
                });
                loanDetailGrid.stopEditing();
                loanDetailDS.insert(0, record);
                loanDetailGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = loanDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                loanDetailDS.remove(record);
              }
            }]
        });

        //提交
        var submitButton = new Ext.Button({
          text: '提交所有更改',
          tooltip: '提交借货订单的包含产品在内的所有更改信息。',
          iconCls: 'icon-save',
          handler: function(){
            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }
            
            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }

            if (loanFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = loanFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan/updateAfterAudit',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanAfterAuditWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanAfterAuditWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //保存编辑后的基础按钮
        var baseInfoSaveButton = new Ext.Button({
          text: '保存基本信息',
          tooltip: '保存借货订单非产品类基本信息。',
          iconCls: 'temp-save',
          handler: function(){
            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }
            if (loanFormPanel.form.isValid()){
              this.disable();
              loanFormPanel.form.submit({
                success: function(result, resp){
                  if (resp.result.info.indexOf("成功") >= 0) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货订单基本信息，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  } else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: resp.result.info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanAfterAuditWin.destroy();
                },
                failure: function(result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanAfterAuditWin.destroy();
                }
              });
            }
          }
        });
        
        //暂时保存按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editLoanAfterAuditWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var loanFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'edit_loan_after_audit',
          labelWidth: 55,
          width: '950',
          labelAlign: 'right',
          frame : true,
          url: '/loan/updateBaseInfoAfterAudit',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'customer_id'
            }, {
              name: 'description'
            }, {
              name: 'action_date',
              type: 'date',
              dateFormat: 'Y/m/d'
            }, {
              name: 'contract_number'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'sub_type'
            }, {
              name: 'sales_id',
              mapping:'sales.id'
            }, {
              name: 'delivery_address'
            },{
              name: 'lock_version'
            }]),
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .6,
                  layout: 'form',
                  border: false,
                  items: [toCustomer]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [addCustomerButton]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [contractNumber]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [linkman]
                }, {
                  columnWidth: .4,
                  layout: 'form',
                  border: false,
                  items: [phone]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [sales]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [loanDetailGrid]
                }]
            },loanId,temporary,version],
          buttons: [submitButton,baseInfoSaveButton,closeButton]
        });

        customerStore.load({callback: function(record, options, success){
            if(success){
              salesStore.load({callback: function(record, options, success){
                  if(success){
                    loanFormPanel.form.load({
                      url: '/loan/getLoanById?id=' + <%=params[:id]%>,
                      method : 'GET',
                      waitMsg: '正在载入数据...',
                      success: function(form, action){
                      },
                      failure: function(form, action){
                        Ext.MessageBox.show({
                          title: '消息',
                          msg: "信息加载失败！",
                          buttons: Ext.MessageBox.OK,
                          icon: Ext.MessageBox.WARNING
                        });
                        editLoanAfterAuditWin.destroy();
                      }
                    });
                  }else{
                    Ext.Msg.alert('操作','失败！');
                  }
                }});
            }else{
              Ext.Msg.alert('操作','失败！');
            }
          }});

        loanFormPanel.render('edit_loan_after_audit');
      })
    </script>
  </head>
  <body>
    <div id="edit_loan_after_audit"></div>
  </body>
</html>